
from textual.app import ComposeResult
from textual.screen import ModalScreen
from textual.widgets import Button, Static
from textual.containers import Vertical, Center
from textual.widgets._button import ButtonVariant
from textual.binding import Binding

from rich.text import TextType

class TextDialog(ModalScreen[None]):
    '''显示文本的对话框'''

    DEFAULT_CSS = """
    TextDialog {
        align: center middle;
    }

    TextDialog Center {
        width: 100%;
    }

    TextDialog > Vertical {
        background: $boost;
        min-width: 30%;
        width: auto;
        height: auto;
        border: round $primary;
    }

    TextDialog Static {
        width: auto;
    }

    TextDialog .spaced {
        padding: 1 4;
    }

    TextDialog #message {
        min-width: 100%;
    }
    """

    BINDINGS = [
        Binding("space", "dismiss", "", show=False),
    ]

    def __init__(self, title: TextType, message: TextType) -> None:
        '''构造函数'''
        super().__init__()
        self._title = title
        self._message = message

    @property
    def button_style(self) -> ButtonVariant:
        '''按钮样式'''
        return "primary"

    def compose(self) -> ComposeResult:
        '''构建界面'''
        with Vertical():
            with Center():
                yield Static(self._title, id="title", classes="spaced")
            yield Static(self._message, id="message", classes="spaced")
            with Center(classes="spaced"):
                yield Button("OK", variant=self.button_style)

    def on_mount(self) -> None:
        '''挂载后，聚焦按钮'''
        self.query_one(Button).focus()

    def on_button_pressed(self) -> None:
        '''按钮被点击时，关闭当前屏幕
        Tips: dismiss 是 Textual 的内置方法，用于关闭当前屏幕
        '''
        self.dismiss(None)